﻿using AutoMapper;
using Himall.Core;
using Himall.Core.Plugins.Message;
using Himall.IServices;
using System;
using System.Collections.Generic;
using Himall.Model;
using System.Linq;
using Himall.IServices.QueryModel;
using Himall.Application.Mappers;
using Himall.DTO;
using Himall.CommonModel;
using Himall.Entity;

[assembly: OnHimallStartMethod(typeof(Himall.Application.MemberApplication), "InitMessageQueue")]
namespace Himall.Application
{
    public class MemberApplication
    {
		#region 静态字段
		private static IMemberService _iMemberService = ObjectContainer.Current.Resolve<IMemberService>();
		#endregion

        #region 插件相关
        /// <summary>
        /// 获取会员认证情况
        /// </summary>
        /// <param name="UserId">会员ID</param>
        /// <returns></returns>
        public static Himall.DTO.MemberAccountSafety GetMemberAccountSafety(long UserId)
        {
            Himall.DTO.MemberAccountSafety model = new Himall.DTO.MemberAccountSafety();
            model.UserId = UserId;
            List<MemberContactsInfo> lmMemberContactsInfo = MessageApplication.GetMemberContactsInfo(UserId);

            foreach (MemberContactsInfo item in lmMemberContactsInfo)
            {
                if (item.ServiceProvider.Contains("SMS"))
                {
                    model.Phone = item.Contact;
                    model.BindPhone = true;
                }
                else if (item.ServiceProvider.Contains("Email"))
                {
                    model.Email = item.Contact;
                    model.BindEmail = true;
                }
            }

            return model;
        }


        /// <summary>
        /// 发送验证码，认证管理员
        /// </summary>
        /// <param name="pluginId">信息类别</param>
        /// <param name="destination">联系号码</param>
        /// <param name="UserName">会员账号</param>
        /// <param name="SiteName">站点设置</param>
        /// <returns></returns>
        public static Himall.CommonModel.SendMemberCodeReturn SendMemberCode(string pluginId, string destination, string UserName, string SiteName)
        {
            //判断号码是否绑定
            if (MessageApplication.GetMemberContactsInfo(pluginId, destination, UserTypes.General) != null)
            {
                return Himall.CommonModel.SendMemberCodeReturn.repeat;
            }
            else
            {
                var timeout = CacheKeyCollection.MemberPluginReBindTime(UserName, pluginId); //验证码超时时间
                if (Core.Cache.Get(timeout) != null)
                {
                    return Himall.CommonModel.SendMemberCodeReturn.limit;
                }
                var checkCode = new Random().Next(10000, 99999);
                Log.Debug("Code:" + checkCode);
                var cacheTimeout = DateTime.Now.AddMinutes(15);
                Core.Cache.Insert(CacheKeyCollection.MemberPluginCheck(UserName, pluginId + destination), checkCode, cacheTimeout);
                var user = new MessageUserInfo() { UserName = UserName, SiteName = SiteName, CheckCode = checkCode.ToString() };
                MessageApplication.SendMessageCode(destination, pluginId, user);
                Core.Cache.Insert(CacheKeyCollection.MemberPluginReBindTime(UserName, pluginId), "0", DateTime.Now.AddSeconds(110));//验证码超时时间
                return Himall.CommonModel.SendMemberCodeReturn.success;
            }
        }

        /// <summary>
        /// 验证码验证，认证管理员
        /// </summary>
        /// <param name="pluginId">信息类别</param>
        /// <param name="code">验证码</param>
        /// <param name="destination">联系号码</param>
        /// <param name="userId">会员ID</param>
        /// <returns></returns>
        public static int CheckMemberCode(string pluginId, string code, string destination, long userId)
        {
            var member = _iMemberService.GetMember(userId);
            int result = 0;
            var cache = CacheKeyCollection.MemberPluginCheck(member.UserName, pluginId + destination);
            var cacheCode = Core.Cache.Get(cache);
            if (cacheCode != null && cacheCode.ToString() == code)
            {
                if (MessageApplication.GetMemberContactsInfo(pluginId, destination, UserTypes.General) != null)
                {
                    result = -1;
                }
                else
                {
                    if (pluginId.ToLower().Contains("email"))
                    {
                        member.Email = destination;
                    }
                    else if (pluginId.ToLower().Contains("sms"))
                    {
                        member.CellPhone = destination;
                    }

                    _iMemberService.UpdateMember(member);

                    MessageApplication.UpdateMemberContacts(new MemberContactsInfo() { Contact = destination, ServiceProvider = pluginId, UserId = userId, UserType = UserTypes.General });

                    Core.Cache.Remove(CacheKeyCollection.MemberPluginCheck(member.UserName, pluginId));
                    Core.Cache.Remove(CacheKeyCollection.Member(userId));//移除用户缓存
                    Core.Cache.Remove("Rebind" + userId);
                    result = 1;
                }
            }
            return result;
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="pluginId">信息类别</param>
        /// <param name="destination">联系号码</param>
        /// <param name="UserName">会员账号</param>
        /// <param name="SiteName">站点设置</param>
        /// <returns></returns>
        public static bool SendCode(string pluginId, string destination, string UserName, string SiteName)
        {
            var timeout = CacheKeyCollection.MemberPluginAuthenticateTime(UserName, pluginId); //验证码超时时间
            if (Core.Cache.Get(timeout) != null)
            {
                return false;
            }
            var checkCode = new Random().Next(10000, 99999);
            Log.Debug("Code:" + checkCode);
            var cacheTimeout = DateTime.Now.AddMinutes(15);
            Core.Cache.Insert(CacheKeyCollection.MemberPluginAuthenticate(UserName, pluginId + destination), checkCode, cacheTimeout);
            var user = new MessageUserInfo() { UserName = UserName, SiteName = SiteName, CheckCode = checkCode.ToString() };
            MessageApplication.SendMessageCode(destination, pluginId, user);
            Core.Cache.Insert(CacheKeyCollection.MemberPluginAuthenticateTime(UserName, pluginId), "0", DateTime.Now.AddSeconds(110));//验证码超时时间
            return true;
        }

        /// <summary>
        /// 验证码验证
        /// </summary>
        /// <param name="pluginId">信息类别</param>
        /// <param name="code">验证码</param>
        /// <param name="destination">联系号码</param>
        /// <param name="userId">会员ID</param>
        /// <returns></returns>
        public static int CheckCode(string pluginId, string code, string destination, long userId)
        {
            var member = _iMemberService.GetMember(userId);
            int result = 0;
            var cache = CacheKeyCollection.MemberPluginAuthenticate(member.UserName, pluginId + destination);
            var cacheCode = Core.Cache.Get(cache);
            if (cacheCode != null && cacheCode.ToString() == code)
            {
                Core.Cache.Remove(CacheKeyCollection.MemberPluginAuthenticate(member.UserName, pluginId));
                Core.Cache.Remove(CacheKeyCollection.Member(userId));//移除用户缓存
                Core.Cache.Remove("Rebind" + userId);
                result = 1;
            }
            return result;
        }
        #endregion

        #region 会员相关
        /// <summary>
        /// 获取会员信息
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public static Himall.DTO.Members GetMembers(long UserId)
        {
            //  var model = _iMemberService.GetMember(UserId);
            // Mapper.CreateMap<Himall.Model.UserMemberInfo, Himall.DTO.Members>();
            // return Mapper.Map<Himall.Model.UserMemberInfo, Himall.DTO.Members>(model);

            var model = _iMemberService.GetMember(UserId);
            var m = Mapper.Map<UserMemberInfo, Himall.DTO.Members>(model);

            if (model.InviteUserId.HasValue)
            {
                var inviteUser = _iMemberService.GetMember(model.InviteUserId.Value);
                if (inviteUser != null)
                {
                    m.InviteUserName = inviteUser.UserName;
                }
            }
            m.MemberLabels = MemberLabelApplication.GetMemberLabelList(UserId).Models;
            var userInte = MemberIntegralApplication.GetMemberIntegral(UserId);
            var userGrade = MemberGradeApplication.GetMemberGradeByUserIntegral(userInte.HistoryIntegrals);
            m.GradeName = userGrade.GradeName;//方法内部包含获取等级的方法
            return m;
        }
        /// <summary>
        /// 根据用户id获取用户信息
        /// </summary>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public static List<DTO.Members> GetMembers(IEnumerable<long> userIds)
        {
			var result= _iMemberService.GetMembers(userIds).Map<List<DTO.Members>>();
			return result;
        }

        /// <summary>
        /// 更新会员信息
        /// </summary>
        /// <param name="model"></param>
        public static void UpdateMember(Himall.DTO.Members model)
        {
            var mm = _iMemberService.GetMember(model.Id);
            mm.Email = model.Email;
            mm.CellPhone = model.CellPhone;
            mm.RealName = model.RealName;
            _iMemberService.UpdateMember(mm);
        }     


        /// <summary>
        /// 验证支付密码
        /// </summary>
        /// <param name="memid"></param>
        /// <param name="payPwd"></param>
        public static bool VerificationPayPwd(long memid, string payPwd)
        {
            return _iMemberService.VerificationPayPwd(memid, payPwd);
        }

		/// <summary>
		/// 是否有支付密码
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public static bool HasPayPwd(long id)
		{
			return _iMemberService.HasPayPwd(id);
		}



        /// <summary>
        /// 更新会员信息新方法必须
        /// </summary>
        /// <param name="model"></param>
        public static void UpdateMemberInfo(MemberUpdate model)
        {
            var mm = _iMemberService.GetMember(model.Id);//先查询
                                                         // mm.Email = model.Email;
                                                         //  mm.CellPhone = model.CellPhone;
            mm.RealName = model.RealName;
            mm.Nick = model.Nick;
            mm.QQ = model.QQ;
            if (model.BirthDay.HasValue)
                mm.BirthDay = model.BirthDay;
            mm.Occupation = model.Occupation;
            mm.Sex = model.Sex;
            _iMemberService.UpdateMemberInfo(mm);
        }

        #region 分销用户关系
    
        /// <summary>
        /// 更新用户关系
        /// </summary>
        /// <param name="id">关系信息编号列表</param>
        /// <param name="userId">买家编号</param>
        public static void UpdateDistributionUserLink(IEnumerable<long> ids, long userId)
        {
            _iMemberService.UpdateDistributionUserLink(ids, userId);
        }
        #endregion

        /// <summary>
        /// 修改支付密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="password"></param>
        public static void ChangePayPassword(long id, string password)
        {
            _iMemberService.ChangePayPassword(id, password);
        }
        

        /// <summary>
        /// 根据查询条件分页获取会员信息(兼容老版本)
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public static QueryPageModel<UserMemberInfo> GetMembers(MemberQuery query)
        {
            return _iMemberService.GetMembers(query);
        }



        /// <summary>
        /// 根据查询条件分页获取会员信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public static QueryPageModel<DTO.Members> GetMemberList(MemberQuery query)
        {
            if (query.GradeId.HasValue)
            {
                var expenditureRange = MemberApplication.GetMemberGradeRange(query.GradeId.Value);
                query.MinIntegral = expenditureRange.MinIntegral;
                query.MaxIntegral = expenditureRange.MaxIntegral;
            }
            var list = _iMemberService.GetMembers(query);
            var members = Mapper.Map<QueryPageModel<DTO.Members>>(list);
            var grades = MemberGradeApplication.GetMemberGradeList();
            foreach (var m in members.Models)
            {
                var memberIntegral = MemberIntegralApplication.GetMemberIntegral(m.Id);
                m.GradeName = MemberGradeApplication.GetMemberGradeByIntegral(grades, memberIntegral.HistoryIntegrals).GradeName;
                if (memberIntegral != null)
                {
                    m.AvailableIntegral = memberIntegral.AvailableIntegrals;
                    m.HistoryIntegral = memberIntegral.HistoryIntegrals;
                }
            }
            return members;
        }

        /// <summary>
        /// 通过会员等级ID获取会员消费范围
        /// </summary>
        /// <param name="gradeId"></param>
        /// <returns></returns>
        public static GradeIntegralRange GetMemberGradeRange(long gradeId)
        {
            return _iMemberService.GetMemberGradeRange(gradeId);
        }


        /// <summary>
        /// 获取一个会员信息
        /// </summary>
        /// <param name="id">会员ID</param>
        /// <returns></returns>
        public static UserMemberInfo GetMember(long id)
        {
            return _iMemberService.GetMember(id);
        }

        /// <summary>
        /// 根据用户id和类型获取会员openid信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="appIdType"></param>
        /// <returns></returns>
        public static DTO.MemberOpenId GetMemberOpenIdInfoByuserId(long userId, AppIdTypeEnum appIdType, string serviceProvider = "")
        {
            var model = _iMemberService.GetMemberOpenIdInfoByuserId(userId, appIdType,serviceProvider);
            return AutoMapper.Mapper.Map<DTO.MemberOpenId>(model);
        }

  
		/// <summary>
		/// 修改最后登录时间
		/// </summary>
		/// <param name="id"></param>
		public static void UpdateLastLoginDate(long id)
		{
			_iMemberService.UpdateLastLoginDate(id);
		}


        /// <summary>
        ///根据用户ID从缓存获取用户信息
        /// </summary>
        /// <returns></returns>
        public static UserMemberInfo GetUserByCache(long id)
        {
            return _iMemberService.GetUserByCache(id);
        }


        /// <summary>
        /// 根据服务商返回的OpenId获取系统中对应的用户
        /// </summary>
        /// <param name="serviceProvider">服务商名称</param>
        /// <param name="openId">OpenId</param>
        /// <returns></returns>
        public static UserMemberInfo GetMemberByOpenId(string serviceProvider, string openId)
        {
            return _iMemberService.GetMemberByOpenId(serviceProvider, openId);
        }
        /// <summary>
        /// 根据UnionId、Provider取用户信息
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="UnionId"></param>
        /// <returns></returns>
        public static UserMemberInfo GetMemberByUnionIdAndProvider(string serviceProvider, string UnionId)
        {
            return _iMemberService.GetMemberByUnionId(serviceProvider, UnionId);
        }


        public static IEnumerable<MemberLabelInfo> GetMemberLabels(long memid)
        {
            return _iMemberService.GetMemberLabels(memid);
        }


        public static IEnumerable<int> GetAllTopRegion()
        {
            return _iMemberService.GetAllTopRegion();
        }
        #endregion

		#region 方法
		/// <summary>
		/// 会员购买力列表
		/// </summary>
		/// <param name="query"></param>
		/// <returns></returns>
		public static QueryPageModel<DTO.MemberPurchasingPower> GetPurchasingPowerMember(MemberPowerQuery query)
		{
			var result = _iMemberService.GetPurchasingPowerMember(query);
			QueryPageModel<DTO.MemberPurchasingPower> model = new QueryPageModel<MemberPurchasingPower>();
			model.Total = result.Total;
			model.Models = AutoMapper.Mapper.Map<List<DTO.MemberPurchasingPower>>(result.Models);

			var userIds = model.Models.Select(p => p.Id).ToArray();

			var memberCategorys = _iMemberService.GetMemberBuyCategoryByUserIds(userIds);

			var grades = MemberGradeApplication.GetMemberGradeList();

			var integrals = MemberIntegralApplication.GetMemberIntegrals(userIds);
			foreach (var item in model.Models)
			{
				var intergral = integrals.Where(a => a.MemberId == item.Id).Select(a => a.HistoryIntegrals).FirstOrDefault();
				//填充等级数据
				item.GradeName = MemberGradeApplication.GetMemberGradeByIntegral(grades, intergral).GradeName;

				//填充分类数据
				var categoryNames = memberCategorys.Where(p => p.UserId == item.Id).Select(p => p.CategoryName).Take(3).ToArray();
				if (categoryNames.Length == 0)
					continue;
				item.CategoryNames = string.Join(",", categoryNames);
			}

			return model;
		}

		/// <summary>
		/// 平台获取会员分组信息
		/// </summary>
		/// <returns></returns>
		public static DTO.MemberGroup GetPlatformMemberGroup()
		{
			var memberGroupInfo = _iMemberService.GetMemberGroup();
			return MemberInfoToDto(memberGroupInfo);
		}
		#endregion
        #region 静态方法
   

		static void RefundService_OnRefundSuccessed(long refundId)
		{
			try
			{
				//var refundData = _refundService.GetOrderRefund(refundId);
				//var orderData = _orderService.GetOrder(refundData.OrderId);
			/////	_iMemberService.UpdateNetAmount(refundData.UserId, -refundData.Amount);//减少用户的净消费额

   //           //  OrderApplication.up
   //             if(refundData.RefundMode== OrderRefundInfo.OrderRefundMode.OrderRefund)
   //             {
   //                 _iMemberService.DecreaseMemberOrderNumber(refundData.UserId);//减少用户的下单量
   //             }
			}
			catch (Exception e)
			{
				Log.Error("处理退款成功消息出错", e);
			}
		}

		#endregion

		#region 私有方法
		/// <summary>
		/// 会员分组数据实体到DTO转换
		/// </summary>
		/// <param name=""></param>
		/// <returns></returns>
		private static DTO.MemberGroup MemberInfoToDto(List<MemberGroupInfo> model)
		{
			DTO.MemberGroup memberGroup = new MemberGroup();

			#region 活跃会员
			//一个月活跃会员
			var memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.ActiveOne).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.ActiveOne = 0;
			else
				memberGroup.ActiveOne = memberGroupInfo.Total;

			//三个月活跃会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.ActiveThree).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.ActiveThree = 0;
			else
				memberGroup.ActiveThree = memberGroupInfo.Total;

			//六个月活跃会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.ActiveSix).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.ActiveSix = 0;
			else
				memberGroup.ActiveSix = memberGroupInfo.Total;
			#endregion

			#region 沉睡会员
			// 三个月沉睡会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.SleepingThree).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.SleepingThree = 0;
			else
				memberGroup.SleepingThree = memberGroupInfo.Total;

			// 六个月沉睡会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.SleepingSix).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.SleepingSix = 0;
			else
				memberGroup.SleepingSix = memberGroupInfo.Total;

			// 九个月沉睡会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.SleepingNine).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.SleepingNine = 0;
			else
				memberGroup.SleepingNine = memberGroupInfo.Total;

			// 十二个月沉睡会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.SleepingTwelve).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.SleepingTwelve = 0;
			else
				memberGroup.SleepingTwelve = memberGroupInfo.Total;

			// 二十四个月沉睡会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.SleepingTwentyFour).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.SleepingTwentyFour = 0;
			else
				memberGroup.SleepingTwentyFour = memberGroupInfo.Total;
			#endregion

			#region 生日会员

			// 今日生日会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.BirthdayToday).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.BirthdayToday = 0;
			else
				memberGroup.BirthdayToday = memberGroupInfo.Total;

			// 今月生日会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.BirthdayToMonth).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.BirthdayToMonth = 0;
			else
				memberGroup.BirthdayToMonth = memberGroupInfo.Total;

			// 下月生日会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.BirthdayNextMonth).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.BirthdayNextMonth = 0;
			else
				memberGroup.BirthdayNextMonth = memberGroupInfo.Total;
			#endregion

			#region 注册会员
			// 注册会员
			memberGroupInfo = model.Where(p => p.StatisticsType == MemberStatisticsType.RegisteredMember).FirstOrDefault();
			if (memberGroupInfo == null)
				memberGroup.RegisteredMember = 0;
			else
				memberGroup.RegisteredMember = memberGroupInfo.Total;
			#endregion

			return memberGroup;
		}
		#endregion
    }
}
